<?php
class AuthenticationController extends Zend_Controller_Action
{
	public function indexAction()
    {
        $this->view->title = "Connection";
        $this->view->headTitle($this->view->title);
        $this->_helper->getHelper('layout')->disableLayout();
        
        $request = $this->getRequest();
        $form = new Form_LoginForm();
      
        if($request->isPost()){
            if($form->isValid($this->_request->getPost())){
                $authAdapter = $this->getAuthAdapter();
        
                $username = $form->getValue('username');
                $password = $form->getValue('password');
               
                $authAdapter->setIdentity($username)
                            ->setCredential($password);
                            
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                
                if($result->isValid()){
                    $identity = $authAdapter->getResultRowObject();
                    
                    $authStorage = $auth->getStorage();
                    $authStorage->write($identity);
                    
                    $this->_redirect('index');
                } else {
                    $this->view->errorMessage = "User name or password is wrong.";
                }
            }
        }
        
        
        $this->view->form = $form;
        
    }
    
	private function getAuthAdapter() {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName('users')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password');
                    
        return $authAdapter;
    }
}
